#include<iostream>
using namespace std;
#include<stdlib.h>
#include<string.h>
//剑指offer题2：实现一个函数，将一个字符串中的空格替换成"%20"。例如，当字符串We Are Happy经过变换之后变成We%20Are%20Happy
#include<string>
string& ReplaceSpace(string& str)
{
	for (size_t i = 0; i < str.size(); ++i)
	{
		if (str[i] == ' ')
		str.replace(i, 1, "%20");
	}
	return str;
}
char *ReplaceSpace2(char *str)
{
	int count = 0, size = strlen(str);
	for (size_t i = 0; i < size; ++i)
	{
		if (str[i] == ' ')count++;//先计算出有多少空格
	}
	int size2 = size + 2 * count + 1;
	char *tmp = (char*)malloc(size2);//算出替换后的空间大小
	count = 0;//从下面开始，count做str的index.
	for (size_t i = 0; i <= size2; ++i)
	{
		if (str[count] == ' ')
		{
			tmp[i++] = '%';
			tmp[i++] = '2';
			tmp[i] = '0';
			++count;
			continue;
		}
		tmp[i] = str[count++];
	}
	return tmp;
}
void ReplaceSpace3(char *str, int length)
{                                 //length表示str指向的空间的长度
	if (str == NULL && length <= 0)
	return;
	int increblankspace = 0;//记录空格的个数
	int orilen = 0;//记录原始字符串的个数
	for (int i = 0; str[i] != '\0'; i++) {
		++orilen;
		if (str[i] == ' ')
			++increblankspace;
	}
	int len = increblankspace * 2 + orilen;//记录替换后字符串的长度
	for (int j = orilen; j >= 0;) {
		if (str[j] != ' ')
			str[len--] = str[j];
		else {
			str[len--] = '0';
			str[len--] = '2';
			str[len--] = '%';
		}
		--j;
	}
}
int main()
{
	string str = "We Are Happy";
	cout << ReplaceSpace(str) << endl;
	cout << ReplaceSpace2("We Are Happy") << endl;

	return 0;
}
